package com.lmx.common.oplog.filter;


import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.lmx.common.oplog.ContextHolder;
import com.lmx.common.oplog.util.OpLogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * 审计日志拦截器
 */
public class OpLogFilter implements Filter {
    private Logger log = LoggerFactory.getLogger(getClass());
    /*需要拦截操作日志的url列表*/
    private List<String> needOpRecordUrlList = Lists.newArrayList();

    public void setNeedOpRecordUrlList(List<String> needOpRecordUrlList) {
        this.needOpRecordUrlList = needOpRecordUrlList;
    }

    public void init(FilterConfig filterConfig) {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Stopwatch stopwatch = Stopwatch.createStarted();
        if (needOpRecordUrlList.contains(request.getRequestURI())) {
            try {
                ContextHolder.initContext();
                filterChain.doFilter(servletRequest, servletResponse);
                request.getRequestURI();
                request.getSession();
                Object logObj = ContextHolder.getContext();
                if (logObj instanceof List) {
                    List<List> logList = (List) logObj;
                    if (!CollectionUtils.isEmpty(logList))
                        for (int i = 0; i < logList.size(); ++i) {
                            OpLogUtil.printLog(logList.get(i));
                        }
                }
                ;
                log.debug("operator log end cost: {}s", stopwatch.elapsed().getNano());
            } finally {
                ContextHolder.clear();
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    public void destroy() {
    }
}
